// src\views\sendbox\new-manage\NewsCategory.jsx
// 新闻分类
import React, { useState, useEffect, useContext, useRef } from 'react'
import { Button, Form, Input, Popconfirm, Table } from 'antd';
import {DeleteOutlined } from '@ant-design/icons';
import './NewsCategory.css';
import axios from 'axios';
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };
  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }
  return <td {...restProps}>{childNode}</td>;
};
export default function NewsCategory() {
  const [dataSource, setDataSource] = useState([]);
  useEffect(()=>{
    //获取新闻分类
    axios.get("http://localhost:8888/categories").then(res=>{
      // console.log("新闻分类",res);
      setDataSource(res.data);
    })
  },[]);
  const handleDelete = (id) => {
    // 先页面同步
    const newData = dataSource.filter((item) => item.id !== id);
    setDataSource(newData);
    //后后端同步
    axios.delete(`http://localhost:8888/categories/${id}`)
  };
  const defaultColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      // width: '10%',
      // editable: true,
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      editable:true,
      onCell:(record)=>({
        record,
        // editable:true,
        handleSave:handleSave
      })
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Popconfirm title="确定删除吗?" onConfirm={() => handleDelete(record.id)}>
            <Button danger shape="circle" icon={<DeleteOutlined />}></Button>
          </Popconfirm>
        ) : null,
    },
  ];
 
  // 保存修改内容的回调
  const handleSave = (record) => {
    //打印测试
    console.log("handleSave",record);
    //先修改页面视图
    setDataSource(dataSource.map(item=>{
      if(item.id===record.id){
        return{
          id:item.id,
          title:record.title,
          value:record.title,
        }
      }
      return item
    }));
    // 再修改接口数据
    axios.patch(`http://localhost:8888/categories/${record.id}`,{
      title:record.title,
      value:record.title
    });
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  return (
    <div>
      <Table
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={dataSource}
        columns={columns}
        rowKey={item=>item.id}
      />
    </div>
  )
}
